// vuex权限模块
import {constantRoutes, asnycRoutes, errorRoutes} from '@/router/index'

const state = {
  // 左侧菜单
  routes: [],
  addRoutes: [], //计算好的路由
  isGetUserInfo: false, //获取用户信息，判断token是否正确
}
// 计算单个路由是否有权限
/**
 *
 * @param {any} route 单个路由体
 * @param {string} role 角色
 */
const hasPermission = (route, role) => {
  // 判断当前路由是否有roles
  if (route.meta?.roles) {
    return route.meta.roles.includes(role)
  } else {
    return true
  }
}

// 计算动态路由函数
const filterAsyncRoutes = (routes, role) => {
  let temp = []
  routes.forEach(route => {
    if (hasPermission(route, role)) {
      if (route.children?.length) {
        route.children = filterAsyncRoutes(route.children, role)
      }
      temp.push(route)
    }
  })
  return temp
}
console.log(filterAsyncRoutes(asnycRoutes, 'super'))
const mutations = {
  ADD_ROUTES(state, routes) {
    // 左侧菜单
    state.routes = [...constantRoutes, ...routes]
  },
  // 用户状态信息
  SET_USERINFO_STATE(state, flag) {
    state.isGetUserInfo = flag
  },
}

const actions = {
  // 生成路由动态函数
  generateRoutes({commit}, role) {
    return new Promise((resolve, reject) => {
      // 筛选出动态路由
      let accessRoutes = filterAsyncRoutes(asnycRoutes, role)

      // 存在vuex
      commit('ADD_ROUTES', accessRoutes)

      // 筛选好的路由给router.addRoutes用
      resolve([...accessRoutes, ...errorRoutes])
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
}
